//
//  DDMediaVC.m
//  dingdang
//
//  Created by 阮 沧晖 on 15/7/11.
//  Copyright (c) 2015年 阮 沧晖. All rights reserved.
//

#import "DDMediaVC.h"
#import "PECropViewController.H"
#import "LCVoice.h"
#import "DDNetWorkAPIClient.h"
#import "NSData+Base64.h"

#import "UIImage+External.h"
@interface DDMediaVC ()<UIPickerViewDataSource,UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,PECropViewControllerDelegate>
{
    UIImage * paramImage_process;
    NSMutableArray * array_picker;
    
}
@property(nonatomic,retain) LCVoice * voice;
@end

@implementation DDMediaVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.voice = [[LCVoice alloc] init];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)recordEnd:(id)sender {
    [self.voice stopRecordWithCompletionBlock:^{
        
        if (self.voice.recordTime > 0.0f) {
//            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"\nrecord finish ! \npath:%@ \nduration:%f",self.voice.recordPath,self.voice.recordTime] delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
//            [alert show];
            
            if (_mediaForAudio) {
                
                DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
                NSData *data = [NSData dataWithContentsOfFile:self.voice.recordPath];
                NSString *dataString = [data base64Encoding];
                [network uploadFile:@{@"extName":@"caf",@"data":dataString} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
                
                    if (object) {
                        NSDictionary *dict = (NSDictionary *)object;
                        _mediaForAudio(self.voice.recordPath,[NSString stringWithFormat:@"%f",self.voice.recordTime],[dict objectForKey:@"data"]);
                    }else{
                        NSLog(@"上传失败");
                    }
                    
                }];
                
                
            }
            
        }
        
    }];

}
- (IBAction)recordCancel:(id)sender {
    [self.voice cancelled];
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"取消了" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
    [alert show];
}
- (IBAction)recordStart:(id)sender {
    [self.voice startRecordWithPath:[NSString stringWithFormat:@"%@/Documents/MySound.caf", NSHomeDirectory()]];
}
- (IBAction)openCamera:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        picker.allowsEditing = YES;
        [self presentViewController:picker animated:YES completion:nil];
    }
}
- (IBAction)openPhoto:(id)sender {
    
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (IBAction)openEditor:(id)sender
{
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = paramImage_process;
    
    UIImage *image = paramImage_process;
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    CGFloat length = MIN(width, height);
    controller.imageCropRect = CGRectMake((width - length) / 2,
                                          (height - length) / 2,
                                          length,
                                          length);
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
    
    [self presentViewController:navigationController animated:YES completion:nil];
}

#pragma mark - picker dataSource & delegate
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return array_picker.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return array_picker[row];
}

#pragma mark - pickerImage Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    image = [image fixOrientation];
    //image = [image imageByScaleForSize:CGSizeMake(self.view.frame.size.width * 2, self.view.frame.size.height * 2)];
    
    paramImage_process = image;
    [picker dismissViewControllerAnimated:YES completion:^{
        [self openEditor:nil];
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -  PECropViewControllerDelegate
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{
    [controller dismissViewControllerAnimated:YES completion:nil];
    paramImage_process = croppedImage;
    
    
    DDNetWorkAPIClient *network = [[DDNetWorkAPIClient alloc]init];
    NSData *data = UIImageJPEGRepresentation(paramImage_process, 0.1);
    NSString *dataString = [data base64Encoding];
    
//    if (_mediaForPhoto) { //先显示 后提交服务器
//        _mediaForPhoto(croppedImage,@"");
//    }
    
    [network uploadImage:@{@"extName":@"jpg",@"data":dataString} completionBlock:^(BOOL isSuccess, NSString *message, NSString *status, id object) {
        
        if (object) {
            NSDictionary *dict = (NSDictionary *)object;
            if (_mediaForPhoto) {
                _mediaForPhoto(croppedImage,[dict objectForKey:@"data"]);
            }
        }else{
            NSLog(@"上传失败");
        }
        
    }];
    
    
}

- (void)cropViewControllerDidCancel:(PECropViewController *)controller{
    [controller dismissViewControllerAnimated:YES completion:nil];
}
@end
